<script setup>
import { onMounted, ref ,watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { pageQuery,addEmp,getById,updataById,deleteByIds} from '@/api/emp';
import { queryAll } from '@/api/dept'
const empList = ref([])
const searchForm = ref({
  name: "",
  gender: "",
  daterange: [],
  begin: "",
  end: ""
})
const token = ref('');
const emp = ref({ 
  //dialog里表单所绑定的数据对象。后期要提交到后端，所以必须与API接口文档里的参数一致
  "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
});
//添加工作经历
const addExpr=() => {
  
  emp.value.exprList.push({exprDate:[],company:"",job:"",begin:"",end:""})
};
//删除工作经历
const deleteExpr = (index) =>{
  emp.value.exprList.splice(index,1)
}
watch(()=>emp.value.exprList,(newV,oldV)=>{
  newV.forEach(expr =>{
    if(expr.exprDate &&expr.exprDate.length>=2){
      expr.begin = expr.exprDate[0]
      expr.end = expr.exprDate[1]
    }
  })
}),{deep:true};
//绑定性别数据
const genders=ref([
  { label: "男", value: "1" },
  { label: "女", value: "2" }
]);
//绑定职位数据
const jobs=ref([
  {value:"1",name:"班主任"},
  {value:"2",name:"讲师"},
  {value:"3",name:"学工主管"},
   {value:"4",name:"教研主管"},
   {value:"5",name:"咨询师"}

]);
const depts = ref([]); //所有部门选项，需要页面一加载完成后 立即向后端发请求查询得到所有部门
watch(() => searchForm.value.daterange,(newV,oldV) => {
  if(newV && newV.length==2)
  searchForm.value.begin = newV[0];
  searchForm.value.end = newV[1];
})
const dialogFormVisible=ref(false);//弹窗是否可见
const dialogTitle = ref('新增员工');//弹窗标题
//显示新增窗口
const showAddWin = ()=>{
  dialogFormVisible.value = true;
  dialogTitle.value="新增员工"
  emp.value = { "image": "",
  "username": "",
  "name": "",
  "gender": "",
  "job": "",
  "entryDate": "",
  "deptId": "",
  "phone": "",
  "salary": "",
  "exprList": []
};
}
const selectedIds = ref([]);
//显示修改窗口：查询回显
const handleEdit =async (index,row)=>{

  dialogFormVisible.value = true;
  dialogTitle.value="修改员工";
  const result = await getById(row.id);
  if(result.code==1){
    emp.value = result.data;
    let exprList=emp.value.exprList;
    if(exprList&&exprList.length>0){
      exprList.forEach(expr=>{
        expr.exprDate = [expr.begin,expr.end];
      });
    }
  }
}
onMounted( async () => {
  search();
  //加载所有部门
  const result = await queryAll();
  if(result.code==1){
    depts.value = result.data;
  }
  const loginfo = localStorage.getItem('loginfo');
  if(loginfo){
    token.value = JSON.parse(loginfo).token;
  }
})

//图片上传成功
const handleAvatarSuccess = (response,uploadFile)=>{
  emp.value.image = response.data
}
const beforeAvatarUpload = (rawFile) =>{
  if(rawFile.type!== 'image/jpeg'&&rawFile.type!=='image/png'){
    ElMessage.error('上传头像图片只能是 JPG或者PNG 格式!')
    return false
  }else if(rawFile.size/1024/1024>10){
    ElMessage.error('上传头像图片大小不能超过 10MB!')
    return false
  }
  return true

}
const multipleSelection = ref([])

//获取被选中的行记录，将每个行数据的id取出，赋值给selectedIds
const handleSelectionChange = (selection) => {
  selectedIds.value=selection.map(item=>item.id)
}
const batchDelete = async()=>{ 
  ElMessageBox.confirm("确认要删除吗？","警告",{
    type:'warning',
    cancelButtonText:'取消',
    confirmButtonText:'确定'
  }).then(async()=>{ 
    const result = await deleteByIds(selectedIds.value);
    if(result.code==1){
      ElMessage.success("删除成功");
      search();
    }else{
      ElMessage.error("删除失败");
    }
  })
}
const saveEmp = async()=>{ 
  
  let result;
  if(emp.value.id){
    result = await updataById(emp.value);
  }else{
    result = await addEmp(emp.value);
  }
  if(result.code==1){
    ElMessage.success('保存员工成功');
    dialogFormVisible.value = false;
    search();
  }
}
const currentPage = ref(1)
const pageSize = ref(5)
const totalCount = ref(0)
//搜索员工：
const search = async () => {
  //↓↓↓↓↓修改↓↓↓↓↓：向后端发请求时，将真正的当前页码、每页数量 作为参数传递到后端，不再写死
  const result = await pageQuery(searchForm.value, currentPage.value, pageSize.value);
  if (result.code==1) {
      empList.value = result.data.rows;
      totalCount.value = result.data.total; //←将后端返回的结果中，总数量的值 设置给 分页条总数量数据项
  }
}

//每页数量变化时触发
const handleSizechange=(val)=>{
  pageSize.value=val;
  currentPage.value=1;
  search();
}
//当前页码变化时触发
const handleCurrentChange=(val)=>{
  currentPage.value=val;
  search();
}
//重置员工列表
const research = () => { 
  searchForm.value = {
    name: "",
    gender: "",
    daterange: [],
    begin: "",
    end: ""
  };
  //重新查询
  search();
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(' 确认要删除员工？',"警告",{type: "warning",
    confirmButtonText: '确定',
    cancelButtonText:'取消'
  }).then(async ()=>{
    const result = await deleteByIds(row.id);
    if(result.code==1)
  {
    ElMessage.success('删除成功');
    search();
  }else
    ElMessage.error('删除失败');
  }
)};

</script>
<template>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
    <!-- 员工表单 -->
    <el-form label-width="80px">
        <!-- 第1行：用户名和姓名 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="用户名">
                    <el-input v-model="emp.username" placeholder="请输入员工用户名,2-20个字" autocomplete="off" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="姓名">
                    <el-input v-model="emp.name" placeholder="请输入员工姓名,2-10个字" autocomplete="off" />
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第2行：性别和手机号 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="性别" >
                    <el-select v-model="emp.gender" placeholder="请选择性别" style="width:100%">
                        <el-option v-for="g in genders" :label="g.label" :value="g.value" :key="g.value" />
                    </el-select>
                </el-form-item>
              </el-col>
            <el-col :span="12">
                <el-form-item label="手机号">
                    <el-input v-model="emp.phone" placeholder="请输入员工手机号" autocomplete="off" />
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第3行：职位与薪资 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="职位">
                    <el-select v-model="emp.job" placeholder="请选择职位" style="width:100%">
                        <el-option v-for="j in jobs" :label="j.name" :value="j.value" :key="j.value" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="薪资">
                    <el-input v-model="emp.salary"  placeholder="请输入员工薪资" autocomplete="off" />
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第4行：所属部门与入职日期 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="所属部门">
                    <el-select v-model="emp.deptId" placeholder="请选择部门" style="width:100%">
                        <el-option v-for="d in depts" :label="d.name" :value="d.id" :key="d.id"/>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="入职日期">
                    <el-date-picker v-model = "emp.entryDate" type="date" value-format="YYYY-MM-DD" placeholder="选择入职日期"  style="width:100%"/>
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第5行：头像 -->
        <el-row :gutter="20">
            <el-col :span="24">
                <el-form-item label="头像">
                    <el-upload v-model="emp.image" class="avatar-uploader" action="/api/upload" :show-file-list="false"
                              :headers = "{'token':token}" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="emp.image" :src="emp.image" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第6行：添加工作经历按钮 -->
        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="工作经历">
                    <el-button type="success" @click = "addExpr">添加工作经历</el-button>
                </el-form-item>
            </el-col>
        </el-row>
        <!-- 第7行：工作经历 -->
        <el-row :gutter="20" v-for="(expr,index) in emp.exprList" :key="index">
            <el-col :span="9">
                <el-form-item label="时间" label-width="70px">
                    <el-date-picker  value-format="YYYY-MM-DD" type="daterange" v-model="expr.exprDate" range-separator="到" 
                                    start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="公司" label-width="50px">
                    <el-input v-model="expr.company" placeholder="请输入公司名称" autocomplete="off" />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="职位" label-width="50px">
                    <el-input v-model="expr.job" placeholder="请输入职位" autocomplete="off" />
                </el-form-item>
            </el-col>
            <el-col :span="3">
                <el-button type="danger" @click="deleteExpr(index)">删除</el-button>
            </el-col>
        </el-row>
    </el-form>
    <template #footer>
        <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEmp">保存</el-button>
        </div>
    </template>
</el-dialog>

  <el-button type="primary" @click="showAddWin">+新增员工</el-button>
  <el-button type="primary" @click="batchDelete">-批量删除</el-button>

  <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <el-form-item label="用户名">
      <el-input v-model="searchForm.name" placeholder="请输入员工姓名" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable>
      <el-option label = "男" value="1"/>
      <el-option label = "女" value="2"/>
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期">
      <el-date-picker
        v-model="searchForm.daterange" value-format="YYYY-MM-DD"
        type="daterange" range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期"
        clearable
        />
    </el-form-item>
    <el-form-item>
      
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="research">重置</el-button>
    </el-form-item>
  </el-form>

   <el-table :data="empList" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" prop="id" width="55" />
    <el-table-column label="姓名"  prop="name" width="55">
    </el-table-column>
<el-table-column label="性别" width="100">  
  <template #default="scope"> 
    {{ scope.row.gender==1?'男':'女' }}
  </template>
</el-table-column>
<el-table-column label="头像" width="100">
  <template #default = "scope">
    <el-image :src="scope.row.image" width="50" alt=""></el-image>
  </template>
  </el-table-column>
    <el-table-column label="所属部门" prop="dept.name" width="180"></el-table-column>
      <el-table-column label="职位">  
        <template #default = "scope">
        <span v-if="scope.row.job == 1">班主任</span>
            <span v-else-if="scope.row.job == 2">讲师</span>
            <span v-else-if="scope.row.job == 3">学工主管</span>
            <span v-else-if="scope.row.job == 4">教研主管</span>
            <span v-else>咨询师</span>
        </template>
      </el-table-column>
          <el-table-column label="入职日期" prop="entryDate"></el-table-column>
    <el-table-column label="最后操作时间" prop="updateTime"></el-table-column>
    <el-table-column label="操作">
        <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :page-sizes="[5, 10, 20, 40]"
               layout="sizes, total, prev, pager, next, jumper" :total="totalCount"  
               @size-change="handleSizechange" @current-change="handleCurrentChange" />


</template>

<style scoped>

.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>
